package com.lelouch.bestpractice.mongorepository.controller;

import com.lelouch.bestpractice.mongorepository.tools.MD5Tool;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;


/**
 * 登陆控制器
 *
 * @author lcy
 * @create 2018-09-17 13:56
 */
@Controller
@RequestMapping("/shiro")
@Slf4j
public class LoginController {
    @RequestMapping("/loginindex")
    public String loginindex() {
        return "login";
    }

    @RequestMapping("/list")
    public String list() {
        return "list";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password) {
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, MD5Tool.str2Md5(password));
            token.setRememberMe(true);
            //System.out.println(token.hashCode());
            try {
                log.info("对用户[" + username + "]进行登录验证..验证开始");
                currentUser.login(token);
                log.info("对用户[" + username + "]进行登录验证..验证通过");

                return "redirect:list";
            } catch (Exception e) {
                //unexpected condition?  error?
                System.out.println("登陆失败");
                return "redirect:loginindex";
            }


        }
        return "redirect:list";
    }


    @RequestMapping("/logout")
    public String logout(HttpSession session, Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
//        session.removeAttribute("user");
        model.addAttribute("msg", "安全退出！");
        return "redirect:loginindex";
    }


}
